import Axios from "axios";
import qs from "qs";
import Md5 from "md5";

const KUYUAN_TOKEN = "shanxikuyuanwangluokeji";

/**
 * 获取请求sign
 * @param param
 * @returns {*}
 */
function getSign (param) {
    let keys = Object.keys(param).sort();
    let key_str = '';
    for (let i = 0; i < keys.length; i++) {
        key_str += keys[i];
    }
    key_str += KUYUAN_TOKEN;
    return Md5(key_str).toUpperCase();
}

/**
 * 请求
 * @param action
 * @param param
 * @param set_url 请求链接
 * @returns {Promise<AxiosResponse<T>>}
 */
const request = function(action,param,set_url){
    let actions = action.split("/");
    let url = set_url ? set_url : document.getElementById("louie").getAttribute("data-url");
    let params = {
        pages:actions[0],
        doing:actions[1]
    };
    let send_data = Object.assign(params,param);
    send_data.sign = getSign(send_data);
    return Axios.post(url,qs.stringify(send_data));
};

/**
 * 上传文件
 * @param data
 * @returns {Promise<AxiosResponse<T>>}
 */
const upload = function(data) {
    let url = document.getElementById("louie").getAttribute("data-url");
    return Axios.post(url, data, {
        headers: {'Content-Type': 'multipart/form-data'}
    });
}

export {request,upload};
